<template>
  <div class="profile-container">
    <div class="page-header">
      <h1>个人信息</h1>
      <p>查看和管理您的个人信息</p>
    </div>
    
    <div class="profile-content">
      <el-card class="profile-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
            <el-button
              type="primary"
              :icon="Edit"
              @click="editMode = !editMode"
            >
              {{ editMode ? '取消编辑' : '编辑信息' }}
            </el-button>
          </div>
        </template>
        
        <div class="profile-form">
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            :disabled="!editMode"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="profileForm.username"
                placeholder="请输入用户名"
                :disabled="true"
              />
            </el-form-item>
            
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="profileForm.name"
                placeholder="请输入真实姓名"
              />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="profileForm.email"
                placeholder="请输入邮箱"
              />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="profileForm.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            
            <el-form-item v-if="editMode">
              <el-button
                type="primary"
                :loading="userStore.loading"
                @click="handleSave"
              >
                保存修改
              </el-button>
              <el-button @click="handleCancel">
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <h3>预约统计</h3>
        </template>
        
        <div class="stats-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ totalBookings }}</div>
                <div class="stat-label">总预约次数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ activeBookings }}</div>
                <div class="stat-label">当前预约</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">¥{{ totalSpent }}</div>
                <div class="stat-label">总消费金额</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useCourtStore } from '@/stores/court'

const userStore = useUserStore()
const courtStore = useCourtStore()

// 状态
const editMode = ref(false)
const profileFormRef = ref()
const userBookings = ref([])

const profileForm = reactive({
  username: '',
  name: '',
  email: '',
  phone: ''
})

const profileRules = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 计算属性
const totalBookings = computed(() => {
  return userBookings.value.length
})

const activeBookings = computed(() => {
  return userBookings.value.filter(booking => booking.status === 'confirmed').length
})

const totalSpent = computed(() => {
  return userBookings.value.reduce((total, booking) => {
    return total + (booking.status === 'confirmed' ? booking.time_slots?.price || 0 : 0)
  }, 0)
})

// 方法
const loadProfileData = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    profileForm.username = userInfo.username || ''
    profileForm.name = userInfo.name || ''
    profileForm.email = userInfo.email || ''
    profileForm.phone = userInfo.phone || ''
  }
}

const loadUserBookings = async () => {
  try {
    userBookings.value = await courtStore.getUserBookings()
  } catch (error) {
    console.error('加载用户预约失败:', error)
  }
}

const handleSave = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      const result = await userStore.updateProfile(profileForm)
      if (result.success) {
        ElMessage.success(result.message)
        editMode.value = false
      } else {
        ElMessage.error(result.message)
      }
    }
  })
}

const handleCancel = () => {
  editMode.value = false
  loadProfileData()
}

// 监听用户信息变化
watch(() => userStore.userInfo, () => {
  loadProfileData()
}, { immediate: true })

onMounted(async () => {
  loadProfileData()
  await loadUserBookings()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 1.1rem;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card,
.stats-card {
  transition: transform 0.3s ease;
}

.profile-card:hover,
.stats-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.profile-form {
  padding: 20px 0;
}

.stats-content {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .stat-item {
    margin-bottom: 10px;
  }
}
</style>
